<?php

namespace App\Http\Controllers\Api\User;

use App\Http\Controllers\Controller;
use App\Models\Recruit;
use App\Models\User;
use App\Models\UserCollectRecruit;
use App\Services\CollectService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class CollectController extends Controller
{
    public function collect(Request $request): JsonResponse
    {
        $rule        = [
            "user_id"    => "required|integer|exists:user,id",
            "recruit_id" => "required|integer|exists:recruit,id",
            "collect_id" => "present|nullable|integer"
        ];
        $input       = $request->input();
        $validateRet = Validator::make($input, $rule);
        if ($validateRet->fails()) {
            return result(1, $validateRet->errors()->first());
        }

        try {
            $data = (new CollectService())->collectRecruit($input);
        } catch (\Exception $e) {
            return result(1, $e->getMessage());
        }

        return result(0, '操作成功', $data);
    }

    public function list(Request $request)
    {
        $rule        = [
            "user_id"                 => "required|integer|exists:user,id",
        ];
        $input       = $request->input();
        $validateRet = Validator::make($input, $rule);
        if ($validateRet->fails()) {
            return result(1, $validateRet->errors()->first());
        }

        $page  = $request->input('page', 1);
        $limit = $request->input('limit', 10);
        $sortField  = $request->input('sort', 'user_collect_recruit.updated_at');
        $orderRule = $request->input('order', 'desc');

        $userTableColumns = ['id', 'nickname', 'avatar'];
        $verifyTableColumns = ['id', 'user_id', 'type'];
        $recruitTableColumns = ['recruit.id', 'recruit.city', 'recruit.title', 'recruit.created_at', 'recruit.user_id'];

        try {
            $data = (new CollectService())->collectRecruitList($input, $page, $limit, $sortField, $orderRule,
                $userTableColumns, $verifyTableColumns, $recruitTableColumns);
        } catch (\Exception $e) {
            return result(1, $e->getMessage());
        }

        return result(0, 'ok', $data);
    }
}
